<template>
  <div class="card-management">
    <div class="page-header">
      <h2>银行卡管理</h2>
      <div class="header-actions">
        <button @click="showAddModal = true" class="btn btn-primary">
          <span class="btn-icon">➕</span>
          新增银行卡
        </button>
        <button @click="exportToCSV" class="btn btn-secondary">
          <span class="btn-icon">📊</span>
          导出CSV
        </button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-box">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索卡号..."
          class="search-input"
        />
        <button @click="searchCards" class="search-btn" :disabled="true">🔍</button>
      </div>
      <div class="filter-options">
        <select v-model="statusFilter" class="filter-select">
          <option value="">全部状态</option>
          <option value="0">正常</option>
          <option value="1">挂失</option>
        </select>
        <select v-model="typeFilter" class="filter-select">
          <option value="">全部类型</option>
          <div v-for="card in this.savings">
            <option :value="card.savingName">{{card.savingName}}</option>
          </div>
        </select>
      </div>
    </div>

    <!-- 银行卡列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>卡号</th>
            <th>存款类型</th>
            <th>开户日期</th>
            <th>余额</th>
            <th>状态</th>
            <th>客户姓名</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="card in filteredCards" :key="card.id">
            <td>{{ card.cardID }}</td>
            <td>{{ card.savingName }}</td>
            <td>{{ card.openDate }}</td>
            <td>¥{{ card.balance }}</td>
            <td>
              <span :class="['status-badge', card.status]">
                {{ card.isReportLoss === '1' ? '挂失' : '正常' }}
              </span>
            </td>
            <td>{{ card.customerName }}</td>
            <td>
              <div class="action-buttons">
                <button @click="showPasswordModal(card)" class="btn-icon-btn" title="密码管理">
                  🔐
                </button>
                <button @click="confirmDelete(card.cardID)" class="btn-icon-btn delete" title="删除">
                  🗑️
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 新增/编辑银行卡模态框 -->
    <div v-if="showAddModal" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>新增银行卡</h3>
          <button @click="closeModal" class="close-btn">✕</button>
        </div>
        <form @submit.prevent="saveCard" class="modal-form">
          <div class="form-row">
            <div class="form-group">
              <label>客户身份证 *</label>
              <input v-model="this.formData.PID" type="text" required />
            </div>
            <div class="form-group">
              <label>存款类型 *</label>
              <select v-model="this.formData.savingName" required>
                <option v-for="saving in this.savings" :value="saving.savingName">{{saving.savingName}}</option>
              </select>
            </div>
            <div class="form-group">
              <label>密码 *</label>
              <input v-model="this.formData.pass" type="text" required />
            </div>
          </div>

          <div class="modal-actions">
            <button type="button" @click="closeModal" class="btn btn-secondary">取消</button>
            <button type="submit" class="btn btn-primary">保存</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 密码管理模态框 -->
    <!-- 密码管理模态框 -->
    <div v-if="showPasswordModalFlag" class="modal-overlay" @click="closePasswordModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>密码管理</h3>
          <button @click="closePasswordModal" class="close-btn">✕</button>
        </div>
        <form @submit.prevent="updatePassword" class="modal-form">
          <div class="form-group">
            <label>新密码 *</label>
            <input v-model="newPassword" type="password" required />
          </div>

          <div class="modal-actions">
            <button type="button" @click="closePasswordModal" class="btn btn-secondary">取消</button>
            <button type="submit" class="btn btn-primary">保存</button>
          </div>
        </form>
      </div>
    </div>

  </div>
</template>

<script>
import axios from "axios";

export default {
  name: 'CardManagement',
  data() {
    return {
      cards: [],
      savings: [],
      searchQuery: '',
      statusFilter: '',
      typeFilter: '',
      showAddModal: false,
      showEditModal: false,
      showPasswordModalFlag: false,
      selectedCard: null,
      cardForm: {
        cardNumber: '',
        cardType: '活期',
        openDate: '',
        openAmount: '',
        customerId: '',
        status: 'normal'
      },
      passwordForm: {
        newPassword: '',
        confirmPassword: ''
      },
      editingId: null,
      formData: {
        adminID: 10011001,
        adminName: "admin",
        adminPass: "10011001",
        PID: null,
        pass: "",
        savingName: "活期",
      }
    }
  },
  computed: {
    filteredCards() {
      return this.cards.filter(card => {
        // 确保 searchQuery 存在并避免空值问题
        const matchesSearchQuery =
          (!this.searchQuery ||
           (card.cardID && card.cardID.includes(this.searchQuery)) ||
           (card.customerName && card.customerName.includes(this.searchQuery)));

        // 状态过滤
        const matchesStatusFilter =
          (!this.statusFilter || card.isReportLoss === this.statusFilter);

        // 类型过滤
        const matchesTypeFilter =
          (!this.typeFilter || card.savingName === this.typeFilter);
        console.log(this.typeFilter)
        // 返回所有条件都满足的结果
        return matchesSearchQuery && matchesStatusFilter && matchesTypeFilter;
      });
    }
  },
  mounted() {
    this.updateTime()
    this.refreshInterval = setInterval(this.updateTime, 1000)
  },
  methods: {
    confirmDelete(cardId) {
      alert("确定要删除这张银行卡吗？" + "卡号" + cardId)
      this.deleteCard(cardId);
    },

    async deleteCard(cardId) {
      try {
        this.formData.cardID = cardId
        const response = await axios.post('http://localhost:8057/card/delete' , this.formData);
        if (response.data.code === 200) {
          alert(response.data.msg);
        }else {
          alert(response.data.msg)
        }
      } catch (error) {
        console.error('删除银行卡失败:', error);
        alert('删除银行卡失败，请稍后再试。');
      }
    },


    searchCards() {
      // 搜索逻辑已在computed中实现
    },
    async updateTime() {
      console.log(this.formData)
        try {
          const response = await axios.post('http://localhost:8057/card/selectAllCard', this.formData);
          if (response.data.code === 200) {
            console.log(response)
            this.cards = response.data.data; // 将返回的数据赋值给 customers
          } else {
            console.error('数据获取失败:', response.data.msg);
          }
        } catch (error) {
          console.error('接口请求失败:', error);
        }

        try {
          const response = await axios.post('http://localhost:8057/saving/getAll', this.formData);
          if (response.data.code === 200) {
            console.log(response)
            this.savings = response.data.data;
          } else {
            console.error('数据获取失败:', response.data.msg);
          }
        } catch (error) {
          console.error('接口请求失败:', error);
        }
    },
    getCardTypeName(type) {
      const types = {
        savings: '储蓄卡',
        credit: '信用卡',
        debit: '借记卡'
      }
      return types[type] || type
    },
    
    getStatusName(status) {
      const statuses = {
        normal: '正常',
        lost: '挂失',
        frozen: '冻结'
      }
      return statuses[status] || status
    },
    
    formatDate(dateString) {
      return new Date(dateString).toLocaleDateString('zh-CN')
    },
    
    editCard(card) {
      this.editingId = card.id
      this.cardForm = { ...card }
      this.showEditModal = true
    },

    
    async saveCard() {
      try {
        const response = await axios.post('http://localhost:8057/card/create', this.formData);
        console.log(response)
        if (response.data.code === 200) {
          // 添加成功后刷新客户列表
          alert(response.data.msg + "卡号：" + response.data.data.cardID)
          this.updateTime()
          this.showAddModal = false
          this.formData.PID = ''
          this.formData.pass = ''
          this.formData.savingName = '活期'
        } else {
          alert(response.data.msg);
          console.error('添加失败:', response.data.msg);
        }
      } catch (error) {
        console.error('接口请求失败:', error);
      }
    },

    showPasswordModal(card) {
    this.currentCard = card;
    this.showPasswordModalFlag = true;
    },
    closePasswordModal() {
      this.showPasswordModalFlag = false;
      this.newPassword = '';
    },
    async updatePassword() {
      if (!this.newPassword || this.newPassword.length < 6) {
        alert('新密码必须至少包含6个字符');
        return;
      }

      try {
        const response = await axios.post('http://localhost:8057/card/chancePass', {
          adminID: 10011001,
          adminName: "admin",
          adminPass: "10011001",
          cardID: this.currentCard.cardID,
          newPass: this.newPassword
        });

        if (response.data.code === 200) {
          alert('密码更新成功');
          this.closePasswordModal();
        } else {
          alert('密码更新失败，请稍后再试');
        }
      } catch (error) {
        console.error('更新密码时出错:', error);
        alert('发生错误，无法更新密码');
      }
    },

    
    toggleLostStatus(card) {
      const newStatus = card.status === 'lost' ? 'normal' : 'lost'
      const action = newStatus === 'lost' ? '挂失' : '解挂'
      
      if (confirm(`确定要${action}这张银行卡吗？`)) {
        const index = this.cards.findIndex(c => c.id === card.id)
        if (index !== -1) {
          this.cards[index].status = newStatus
        }
        alert(`银行卡${action}成功！`)
      }
    },
    
    closeModal() {
      this.showAddModal = false
      this.showEditModal = false
      this.cardForm = {
        cardNumber: '',
        cardType: 'savings',
        openDate: '',
        openAmount: '',
        customerId: '',
        status: 'normal'
      }
      this.editingId = null
    },
    
    exportToCSV() {
      const headers = ['卡号', '存款类型', '开户日期', '余额', '状态', '客户名字']
      const csvContent = [
        headers.join(','),
        ...this.filteredCards.map(card => [
          card.cardID,
          card.savingName,
          card.openDate,
          card.balance,
          card.isReportLoss === '1' ? '挂失' : '正常',
          card.customerName
        ].join(','))
      ].join('\n')
      
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', `银行卡数据_${new Date().toISOString().split('T')[0]}.csv`)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      alert('银行卡数据导出成功！')
    }
  }
}

</script>

<style scoped>
/* General Page Styling */
.card-management {
  padding: 32px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 60px); /* Adjust based on your header height */
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}

/* Page Header */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.page-header h2 {
  font-size: 28px;
  font-weight: 700;
  color: #111827;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* Buttons */
.btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  border: 1px solid transparent;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease-in-out;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px -1px rgba(0, 0, 0, 0.1);
}

.btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
}

.btn-primary {
  background-color: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background-color: #2563eb;
}

.btn-secondary {
  background-color: #ffffff;
  color: #374151;
  border-color: #d1d5db;
}

.btn-secondary:hover {
  background-color: #f9fafb;
}

.btn-icon {
  font-size: 16px;
}

/* Search Section */
.search-section {
  background: #ffffff;
  padding: 24px;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05), 0 2px 4px -2px rgba(0,0,0,0.05);
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-box {
  display: flex;
  flex: 1;
  min-width: 250px;
}

.search-input {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px 0 0 8px;
  font-size: 14px;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.search-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
  z-index: 1;
}

.search-btn {
  padding: 10px 16px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 0 8px 8px 0;
  cursor: pointer;
  margin-left: -1px; /* Overlap border */
}

.filter-options {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.filter-select {
  padding: 10px 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
  background: white;
  min-width: 150px;
}

.filter-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
}

/* Table Styling */
.table-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05), 0 2px 4px -2px rgba(0,0,0,0.05);
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 16px 20px;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
  vertical-align: middle;
}

.data-table th {
  background: #f9fafb;
  font-weight: 600;
  color: #4b5563;
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.data-table tr:hover {
  background-color: #f3f4f6;
}

.data-table td {
  font-size: 14px;
  color: #1f2937;
}

/* Status Badges */
.status-badge {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  display: inline-block;
  text-transform: capitalize;
}

.status-badge.normal {
  background: #dcfce7;
  color: #166534;
}

.status-badge.lost {
  background: #fef9c3;
  color: #854d0e;
}

.status-badge.frozen {
  background: #fee2e2;
  color: #991b1b;
}

/* Action Buttons in Table */
.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-icon-btn {
  padding: 8px;
  font-size: 18px;
  background: none;
  border: none;
  cursor: pointer;
  border-radius: 50%;
  color: #6b7280;
  transition: all 0.2s;
}

.btn-icon-btn:hover {
  background: #e5e7eb;
  color: #1f2937;
}

.btn-icon-btn.delete:hover {
  background: #fee2e2;
  color: #ef4444;
}

/* Modal Styling */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(17, 24, 39, 0.6);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fade-in 0.3s ease;
}

@keyframes fade-in {
  from { opacity: 0; }
  to { opacity: 1; }
}

.modal {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
  animation: modal-pop 0.3s ease-out forwards;
}

@keyframes modal-pop {
  0% { opacity: 0; transform: scale(0.95) translateY(10px); }
  100% { opacity: 1; transform: scale(1) translateY(0); }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  line-height: 1;
  cursor: pointer;
  color: #9ca3af;
  transition: color 0.2s;
}
.close-btn:hover { color: #1f2937; }

.modal-form {
  padding: 24px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 0; /* remove margin-bottom */
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.form-group input,
.form-group select {
  width: 100%;
  box-sizing: border-box; /* Add this */
  padding: 10px 14px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
}

.card-info {
  background: #f9fafb;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid #e5e7eb;
}

.card-info p {
  margin: 4px 0;
  font-size: 14px;
  color: #374151;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

/* Responsive Adjustments */
@media (max-width: 768px) {
  .card-management { padding: 16px; }
  .page-header { flex-direction: column; gap: 16px; align-items: stretch; text-align: center; }
  .header-actions { justify-content: center; }
  
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    max-width: none;
    width: 100%;
  }

  .filter-options {
    flex-direction: column;
    width: 100%;
  }
  
  .data-table { font-size: 12px; }
  .data-table th,
  .data-table td { padding: 10px 12px; }
  
  .form-row {
    grid-template-columns: 1fr;
    gap: 0;
  }
  
  .modal {
    width: 95%;
  }
}
</style> 